package net.nio;

import java.net.InetSocketAddress ;
import java.net.SocketAddress ;
import java.nio.ByteBuffer ;
import java.nio.channels.SelectionKey ;
import java.nio.channels.Selector ;
import java.nio.channels.ServerSocketChannel ;
import java.nio.channels.SocketChannel ;
import java.nio.charset.Charset ;
import java.util.Iterator ;

/**
 * @author 80002165
 * @date 2017年3月2日 上午10:01:06
 * jNIO 简单的客户端程序
 */
public class SampleServer {
    private int port ;
    private SocketAddress address ;
    private void init(){
        port = 9000 ;
        address = new InetSocketAddress(port) ;
    }
    
    private void server(){
        try {
            ServerSocketChannel server = ServerSocketChannel.open() ;
            server.configureBlocking(false) ;
            server.bind(address) ;
            
            Selector selector = Selector.open() ;
            server.register(selector, SelectionKey.OP_ACCEPT) ;
            
            selector.select() ;
            
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator() ;
            while(keyIterator.hasNext()){
                SelectionKey selectedKey = keyIterator.next() ;
                if(selectedKey.isAcceptable()){//与客户端连接成功后才能开始读取客户端信息
                    ServerSocketChannel serverChannel = (ServerSocketChannel) selectedKey.channel() ;
                    //获取一个连接
                    SocketChannel socketChannel = serverChannel.accept() ;
                    //设置为异步
                    socketChannel.configureBlocking(false) ;
                    //注册读取事件
                    socketChannel.register(selector, SelectionKey.OP_READ) ;
                    
                }else if(selectedKey.isReadable()){
                    //读取准备好了，可以开始读取客户端的信息
                    SocketChannel socketChannel = (SocketChannel) selectedKey.channel() ;
                    //建一个缓存，用来接收客户端信息
                    ByteBuffer buffer = ByteBuffer.allocate(1024) ;
                   
                    int count ;
                    while(true){
                        count = socketChannel.read(buffer) ;
                        if(count == -1){//读到流的末尾
                            //断开与客户端连接
//                            selectedKey.cancel();
                            socketChannel.close();
                            break;
                        }
                    }
                   buffer.flip() ;
                   String clientMsg = Charset.forName("UTF-8").decode(buffer).toString() ;
                }
                keyIterator.remove(); 
            }
        } catch (Exception e) {
            e.printStackTrace();
        } ;
        
    }
}
